// NamedRequestDispatcher.java - A RequestDispatcher for a named Servlet.
//
// Copyright (C) 2001-2002  Smart Software Consulting
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
//
// Smart Software Consulting
// 1688 Silverwood Court
// Danville, CA  94526-3079
// USA
//
// http://www.smartsc.com
//

package com.smartsc.http;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.SingleThreadModel;

import com.smartsc.http.HttpRequest;
import com.smartsc.http.HttpResponse;

public class
NamedRequestDispatcher
implements RequestDispatcher
{
	protected
	NamedRequestDispatcher( String name, Servlet servlet )
	{
		this.name = name;
		this.servlet = servlet;
	}

	protected String getName() { return name; }

	public void forward( ServletRequest req, ServletResponse res )
	throws ServletException, IOException
	{
		if( !(res instanceof HttpResponse) )
			throw new IllegalArgumentException();

		HttpResponse httpRes = (HttpResponse)res;

		if( httpRes.isCommitted())
			throw new IllegalStateException( "Response already committed.");

		// Reset response
		res.reset();
		// Invoke servlet
		invokeServlet( req, res );
		// Commit and close response
		httpRes.close();
	}

	public void include( ServletRequest req, ServletResponse res )
	throws ServletException, IOException
	{
		if( !(res instanceof HttpResponse) )
			throw new IllegalArgumentException();

		HttpResponse httpRes = (HttpResponse)res;

		boolean oldIncluding = httpRes.isIncluding();

		httpRes.setIncluding( true );

		try
		{
			invokeServlet( req, res );
		}
		finally
		{
			httpRes.setIncluding( oldIncluding );
		}
	}

	protected
	void
	invokeServlet( ServletRequest req, ServletResponse res )
	throws ServletException, IOException
	{
		if( servlet instanceof SingleThreadModel)
		{
			synchronized( servlet)
			{
				servlet.service( req, res);
			}
		}
		else
		{
			servlet.service( req, res);
		}
	}

	protected String name;
	protected Servlet servlet;
}
